const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const buffersss = require('bufferSplit')


http.createServer((req, res) => {
  let arr = [];
  // console.log(req.headers)
  let fengefu = '--' + req.headers['content-type'].split('; ')[1].split('=')[1];
  let boundary = '--' + req.headers['content-type'].split('; ')[1].split('=')[1];
  console.log(fengefu, boundary);

  req.on('data', buffer => {
    arr.push(buffer);

  })
  req.on('end', () => {
    let buffer = Buffer.concat(arr);
    console.log('buffer', buffer);

    let ress = buffersss.bufferSplit(buffer, fengefu);
    ress.pop();
    ress.shift();
    ress.forEach(buffer => {
      buffer = buffer.slice(2, buffer.length - 2)

      let n = buffer.indexOf('\r\n\r\n');

      let info = buffer.slice(0, n).toString();
      let data = buffer.slice(n + 4);



      console.log('info.indexOf', info.indexOf('r\n'));
      if (info.indexOf('\r\n') != -1) {
        console.log('有文件不？');
        //文件
        let res2 = info.split('\r\n')[0].split('; ');
        let name = res2[1].split('=')[1];
        let filename = res2[2].split('=')[1];

        name = name.substring(1, name.length - 1);
        filename = filename.substring(1, filename.length - 1);

        fs.writeFile(`upload/${filename}`, data, err => {
          if (err) {
            console.log(err);
          } else {
            console.log('上传成功');
          }
        });

      } else {
        //字段
        let name = info.split('; ')[1].split('=')[1]
        name = name.substring(1, name.length - 1)
        // console.log(name);
      }
    })
  })

}).listen(1233)